package com.weir.goods.resource;

import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.jboss.logging.Logger;

import com.weir.goods.entity.GoodsCategory;
import com.weir.quarkus.commons.vo.result.ResultDataVo;

import io.quarkus.cache.CacheResult;

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;

import jakarta.annotation.security.RolesAllowed;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

@Tag(name = "商品分类管理")
@Path("goods/category")
@ApplicationScoped
public class GoodsCategoryResource {
	private static final Logger LOG = Logger.getLogger(GoodsCategoryResource.class);
	
	@CacheResult(cacheName = "category-tree")
	@RolesAllowed("category-tree")
	@GET
	@Path("tree")
	public Response tree() {
//		LOG.info("GoodsCategoryResource");
		return Response.ok().entity(new ResultDataVo<>(200, "ok" , GoodsCategory.tree())).build();
	}
	@Operation(summary = "excel导出")
	@GET
	@Path("/export")
	public Response exportEmployees(){
		LOG.info("Export started");
		List<GoodsCategory> goodsCategoryList = GoodsCategory.listAll();
		try(InputStream is = GoodsCategoryResource.class.getResourceAsStream("/template.xls")){
			try(ByteArrayOutputStream os = new ByteArrayOutputStream()){
				Context context = new Context();
				context.putVar("goodsCategoryList", goodsCategoryList);
				JxlsHelper.getInstance().processTemplate(is, os, context);

				Response resp = Response.ok()
						.type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
						.header("Content-Disposition", "filename=\"export.xls\"").entity(os.toByteArray()).build();

				return resp;
			}
		}catch(Exception e){
			LOG.errorv(e.getMessage());
		}
		return null;
	}

}
